from flask import Flask, render_template, request, escape,jsonify
from panduan import panduan_login
from log_sys import log_request
from weather import weatherapi
from pymysql import connect
import requests
import pandas as pd
import json
import walk

app = Flask(__name__)

def look_over():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="userdb")
	cursor1 = con.cursor()
	sql = "select * from useradmin"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res

@app.route('/')
def hello() -> str:
    return "Hello"

def log_request(req: 'flask_request', res:str) -> None:
	with open('view.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

@app.route('/entry')
def entry() -> 'html':
	title = "一天一项目，天亮就头秃"
	return render_template('entry.html',the_title=title)

@app.route('/login',methods=['GET','POST'])
def login() -> 'html':
	title = "这是登录页面"
	return render_template('login.html',the_title=title)

@app.route('/zhuce',methods=['POST'])
def zhuce() -> "html":
	return render_template('zhuce.html')

@app.route('/luru',methods=['POST'])
def luru():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="userdb")
	cursor2 = con.cursor()
	zhanghao = request.form.get("zhanghao")
	mima = request.form.get("mima")
	sql = "insert into useradmin set name='%s',password='%s'"%(zhanghao,mima)
	cursor2.execute(sql)
	con.commit()
	return render_template("success.html")

@app.route('/yanzheng',methods=['POST'])
def yanzheng() -> 'html':
	title = "登录成功"
	log_request(request,result)
	zhanghao = request.form.get("zhanghao")
	mima = request.form.get("mima")
	a = panduan_login(zhanghao,mima)
	if a == "true":
		return render_template('yanzheng.html',the_title=title)
	else:
		return "登陆失败"

@app.route("/weather",methods=["post"])
def tianqi():
	title = "广州当前天气"
	key='030d60847cc2dbf652a0d1f7e0fce690'
	city='440100'
	extensions='base'
	a=weatherapi(key,city,extensions)
	city=a['lives'][0]['city']
	weather=a['lives'][0]['weather']
	temperature=a['lives'][0]['temperature']
	return render_template('weather.html',the_title=title,the_city=str(city),the_weather=str(weather),the_temperature=str(temperature))

@app.route("/pic",methods=['GET'])
def pic():
	return render_template("picture.html")

@app.route("/result",methods=['POST'])
def result():
	image_url=request.form['pic']
	endpoint = "https://api-ggl.cognitiveservices.azure.com/"
	subscription_key = "8a2abe4e786c40c1936efe083f794112"
	analyze_url = endpoint + "vision/v3.1/analyze"   
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'visualFeatures': 'Categories,Description,Color'}
	data = {'url': image_url}
	response = requests.post(analyze_url, headers=headers,  params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	print(json.dumps(response.json()))
	image_caption = analysis["description"]["captions"][0]["text"].capitalize()
	confidence3 = analysis["description"]["captions"][0]["confidence"]
	return render_template('result.html',pic=str(image_caption),confidence3=str(confidence3),img_url1=image_url)


@app.route('/walking',methods=['GET'])
def walkdata() -> 'html':
	title = "请输入你想规划的步行路线"
	return render_template('buxing.html',the_title=title)

@app.route('/walkresult', methods=['POST'])
def walkresult() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = walk.direction_walking(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    total_walk = walk.total_walk(df)
    total_walk_time = walk.total_walk_time(df)
    route = results['指引'].tolist()
    return render_template('walkresult.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_walk=total_walk,
                           the_total_walk_time=total_walk_time,)

@app.route('/viewlog')
def view_the_log() -> 'html':
	contents =[]
	with open('view.log','r') as log:
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
	title= ['Form data','Remote_addr','User_agent','Results']
	return render_template("viewlog.html",the_title=title,the_data =contents,)

if __name__ == '__main__':
    app.run(debug=True)